import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type {
  loginForm,
  loginResponseData,
  userResponseData
} from '@/api/user/type'
import type { UserState } from './types/type'
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { constantRoute } from '@/router/routes'

const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      userName: '',
      avatar: ''
    }
  },
  actions: {
    async userLogin(data: loginForm) {
      const result: loginResponseData = await reqLogin(data)

      if (result.code === 200) {
        this.token = result.data as string
        SET_TOKEN(this.token)
        return 'success'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    async userInfo() {
      const result: userResponseData = await reqUserInfo()
      if (result.code === 200) {
        this.userName = result.data?.name as string
        this.avatar = result.data?.avatar as string
        return 'success'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    async logout() {
      const result: any = await reqLogout()
      if (result.code === 200) {
        this.token = ''
        this.userName = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'success'
      } else {
        return Promise.reject(new Error(result.message))
      }
    }
  },
  getters: {}
})
export default useUserStore
